﻿using DongFangGuoKai.WMS.IApiService;
using DongFangGuoKai.WMSPlatform.Commn;
using DongFangGuoKai.WMSPlatform.Commn.AppsetingsModule;
using DongFangGuoKai.WMSPlatform.Commn.HttpModule;
using DongFangGuoKai.WMSPlatform.Commn.Md5Module;
using DongFangGuoKai.WMSPlatform.Domain.Enums;
using DongFangGuoKai.WMSPlatform.Domain.TMSModels;
using Newtonsoft.Json;

namespace DongFangGuoKai.WMS.ApiService
{
    /// <summary>
    /// 快递柜系统接口
    /// </summary>
    public class TMSService : ITMSService
    {
        public string RequstUrl;
        public TMSService(ICtmHttpClient client)
        {
            RequstUrl = ConfigManageHelper.TMSServicePath;
            Client = client;
        }
        public ICtmHttpClient Client { get; }


        public BoxResultResoons<BoxResponsData>  OpenBox(BoxOrderModel boxOrderModel)
        {
            var data = CreateSignModel(boxOrderModel);
            string requestUrl = BulidRequstUrl(TMSRequstType.OpenBox);
            return Retry.Execute(() =>
            {
                return Client.Post<BoxResultResoons<BoxResponsData>>(requestUrl, data);
            }, TimeSpan.FromSeconds(3));
        }

        private string BulidRequstUrl(TMSRequstType tMSRequstType)
        {
            switch (tMSRequstType)
            {
                //开门锁定窗格
                case TMSRequstType.OpenBox:
                    return RequstUrl + "/openapi/wmsOpenBox";

                default:
                    break;
            }
            return "";
        }

        private BoxRequest<string> CreateSignModel<T>(T data) where T : class
        {
            // 获取当前时间
            DateTimeOffset currentTime = DateTimeOffset.Now;

            // 转换为与1970年1月1日的时间间隔
            TimeSpan timeSpan = currentTime - new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);

            // 获取时间戳（秒数）
            long timestamp = (long)timeSpan.TotalSeconds;

            BoxRequest<string> model = new BoxRequest<string>();
            model.Timestamp = timestamp;

            model.BizData = JsonConvert.SerializeObject(data);
            var sginStr = model.BizData + model.AppSecret + timestamp;
            // 将字符串转换为字节数组
            byte[] bytes = sginStr.ToMd5ApiSign();
            // 进行BASE64编码
            string base64String = System.Convert.ToBase64String(bytes);
            model.Sign = base64String;

            return model;
        }

    }
}
